<template>
    <div class="app-container">
        <!-- 返回按钮和标题 -->
        <PageHeader back-text="返回" back-type="back" :title="currentAuditInfo.auditTitle || '周总结审核详情'" />


        <!-- 项目详情卡片 -->
        <ProjectDetail :project-info="projectInfo" :loading="projectLoading" />

        <!-- 周总结详情卡片 -->
        <el-card class="mb-6 box-card weeklog-detail-card" v-loading="detailLoading">
            <template #header>
                <div class="card-header">
                    <div class="card-header-left">
                        <span class="title">周总结详情</span>
                        <div class="week-info">
                            <span class="week-label">第{{ weeklogData?.weekOrder || 1 }}周</span>
                        </div>
                    </div>
                    <div class="card-header-right">
                        <ProjectStatusDisplay label="周总结审核状态" :status-options="approval_commit_status"
                            :status-value="weeklogData?.auditStatus" />
                    </div>
                </div>
            </template>

            <div class="weeklog-container">
                <div class="scroll-tip-container">
                    <div class="scroll-tip">
                        <el-icon class="tip-icon">
                            <ArrowLeft />
                        </el-icon>
                        <span class="tip-text">左右滑动查看更多信息</span>
                        <el-icon class="tip-icon">
                            <ArrowRight />
                        </el-icon>
                    </div>
                </div>
                <el-table :data="weeklogRecordList" border style="width: 100%" class="weeklog-table">
                    <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
                    <el-table-column label="回款节点" width="200" align="center" fixed="left" show-overflow-tooltip>
                        <template #default="scope">
                            <span class="receive-name">{{ scope.row.receiveName || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="技术流程" width="200" fixed="left" align="center" show-overflow-tooltip>
                        <template #default="scope">
                            <span class="tech-flow-display">{{ scope.row.techFlow || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="详细工作计划" align="left" width="300" show-overflow-tooltip>
                        <template #default="scope">
                            <el-tooltip :content="scope.row.detailWorkPlan" placement="top"
                                :disabled="!scope.row.detailWorkPlan">
                                <span class="text-overflow">{{ scope.row.detailWorkPlan || '-' }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="计划开始时间" align="center" width="120">
                        <template #default="scope">
                            {{ scope.row.planStartTime ? parseTime(scope.row.planStartTime, '{y}-{m}-{d}') : '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="计划结束时间" align="center" width="120">
                        <template #default="scope">
                            {{ scope.row.planEndTime ? parseTime(scope.row.planEndTime, '{y}-{m}-{d}') : '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="本周工作计划" align="left" width="300" show-overflow-tooltip>
                        <template #default="scope">
                            <span class="text-overflow">{{ scope.row.thisWeekPlan || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="本周完成情况" align="left" width="300">
                        <template #default="scope">
                            <el-tooltip :content="scope.row.thisWeekCase" placement="top"
                                :disabled="!scope.row.thisWeekCase">
                                <span class="text-overflow">{{ scope.row.thisWeekCase || '-' }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="工作内容完成百分比" align="center" width="180">
                        <template #default="scope">
                            <span
                                v-if="scope.row.nodeCompleteRate !== null && scope.row.nodeCompleteRate !== undefined">
                                {{ formatPercentage(Number(scope.row.nodeCompleteRate), 2) }}
                            </span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="下周工作计划" align="left" width="300">
                        <template #default="scope">
                            <el-tooltip :content="scope.row.nextWeekPlan" placement="top"
                                :disabled="!scope.row.nextWeekPlan">
                                <span class="text-overflow">{{ scope.row.nextWeekPlan || '-' }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" align="left" width="300">
                        <template #default="scope">
                            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
                                <span class="text-overflow">{{ scope.row.remark || '-' }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="记录人" align="center" width="120">
                        <template #default="scope">
                            <span>{{ scope.row.recordName || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="记录时间" align="center" width="120">
                        <template #default="scope">
                            {{ scope.row.recordTime ? parseTime(scope.row.recordTime, '{y}-{m}-{d}') : '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="逾期状态" align="center" width="100" fixed="right">
                        <template #default="scope">
                            <el-tag :type="getOverdueStatusType(isOverdue(scope.row.planEndTime))" size="small">
                                {{ getOverdueStatusText(isOverdue(scope.row.planEndTime)) }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <template #empty>
                        <el-empty description="暂无周总结数据" />
                    </template>
                </el-table>
            </div>
        </el-card>

        <!-- 审核操作组件 -->
        <AuditAction v-if="checkContractStatus(currentAuditInfo.auditStatus)" :loading="auditActionLoading"
            @audit="handleAuditAction" />

        <!-- 审核流程组件 -->
        <ApprovalFlowDisplay :business-type="'WEEK-LOG-AUDIT'" :business-id="String(route.params.weeklogId)"
            title="审核流程" :auto-load="true" :show-collapse="true" @data-loaded="handleApprovalDataLoaded"
            @error="handleApprovalError" />
    </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { getWeeklogById } from '@/api/project/log/weeklog';
import { getProDetail } from '@/api/project/init/proInfo';
import type { ProWeeklogVO, ProWeeklogRecordVO } from '@/api/project/log/weeklog/types';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import ProjectDetail from '@/views/project/components/ProjectDetail.vue';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import ProjectStatusDisplay from '@/views/project/components/ProjectStatusDisplay.vue';
import AuditAction from '@/components/AuditAction/index.vue';
import ApprovalFlowDisplay from '@/components/ApprovalFlowDisplay/index.vue';
import { audit } from '@/api/other/approval/index';
import { checkContractStatus } from '@/utils/permission';
import { isOverdue, getOverdueStatusText, getOverdueStatusType } from '@/utils/dateUtils';
import { formatPercentage } from '@/components/NumberInput';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

// 审核信息（仅用于页面标题）
const currentAuditInfo = ref<Partial<any>>({});

// 项目信息
const projectInfo = ref<Partial<ProInfoVO>>({});
const projectLoading = ref(false);

const { proxy } = getCurrentInstance() as any;
const { approval_commit_status } = toRefs(proxy?.useDict('approval_commit_status'));

// 周总结数据
const weeklogData = ref<ProWeeklogVO | null>(null);
const weeklogRecordList = ref<ProWeeklogRecordVO[]>([]);
const detailLoading = ref(false);

// 审核操作加载状态
const auditActionLoading = ref(false);

/**
 * 获取审核信息和周总结详情
 */
const getAuditDetail = async () => {
    const weeklogId = route.params.weeklogId as string;
    if (!weeklogId) {
        ElMessage.error('周总结ID不能为空');
        return;
    }

    try {
        detailLoading.value = true;
        // 根据周总结ID获取周总结详情
        const res = await getWeeklogById(weeklogId);
        const weeklogDataResponse = res.data || {} as ProWeeklogVO;

        // 设置周总结数据
        weeklogData.value = weeklogDataResponse;
        weeklogRecordList.value = weeklogDataResponse.recordList || [];

        // 设置审核信息（仅用于页面标题）
        currentAuditInfo.value = {
            auditTitle: `周总结审核-第${weeklogDataResponse.weekOrder}周`,
            auditStatus: weeklogDataResponse.auditStatus || '1'
        };

        // 获取项目详情
        if (weeklogDataResponse.proId) {
            await getProjectDetail(weeklogDataResponse.proId);
        }
    } catch (error) {
        console.error('获取周总结详情失败:', error);
        ElMessage.error('获取周总结详情失败');
    } finally {
        detailLoading.value = false;
    }
};

/**
 * 获取项目信息
 */
const getProjectDetail = async (proId: string | number) => {
    try {
        projectLoading.value = true;
        const res = await getProDetail(proId);
        projectInfo.value = res.data || {};
    } catch (error) {
        console.error('获取项目信息失败:', error);
    } finally {
        projectLoading.value = false;
    }
};

/**
 * 处理审核操作
 */
const handleAuditAction = async (auditData: { status: string; idea: string }) => {
    try {
        auditActionLoading.value = true;
        await audit({
            businessId: String(route.params.weeklogId),
            businessType: 'WEEK-LOG-AUDIT',
            status: auditData.status,
            idea: auditData.idea
        });

        const message = auditData.status === '1' ? '审核通过成功' : '审核不通过操作完成';
        ElMessage.success(message);
        setTimeout(() => {
            router.push('/');
        }, 1500);
    } catch (error) {
        console.error('审核操作失败:', error);
        ElMessage.error((error as any)?.message || '审核操作失败');
    } finally {
        auditActionLoading.value = false;
    }
};

/**
 * 处理审核数据加载完成事件
 */
const handleApprovalDataLoaded = (data: any[]) => {
    console.log('审核流程数据加载完成:', data);
};

/**
 * 处理审核错误事件
 */
const handleApprovalError = (error: any) => {
    console.error('审核流程加载失败:', error);
};

onMounted(() => {
    getAuditDetail();
});
</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
}

.weeklog-detail-card {
    border-radius: 12px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
        font-size: 16px;
        font-weight: bold;
    }

    .card-header-left {
        display: flex;
        align-items: center;
        gap: 12px;

        .week-info {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 8px;
            border: 1px solid #dee2e6;

            .week-label {
                font-size: 14px;
                font-weight: 500;
                color: #495057;
                white-space: nowrap;
            }
        }
    }
}

.weeklog-container {
    position: relative;
    margin-top: 20px;

    .scroll-tip-container {
        position: absolute;
        left: 0;
        bottom: 24px;
        flex-shrink: 0;
    }

    .scroll-tip {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        font-size: 12px;
        color: #909399;
        background-color: #f5f7fa;
        border: 1px solid #e4e7ed;
        padding: 6px 12px;
        border-radius: 4px;
        display: inline-flex;
    }

    .tip-icon {
        font-size: 14px;
        color: #909399;
    }

    .tip-text {
        font-size: 12px;
        color: #909399;
    }
}

.weeklog-table {
    :deep(.el-table__body-wrapper) {
        max-height: 600px;
        overflow-y: auto;
        overflow-x: auto;
    }

    :deep(.el-table__header-wrapper) {
        position: sticky;
        top: 0;
        z-index: 10;
        background: #fff;
    }

    :deep(.el-table__fixed-header-wrapper) {
        position: sticky;
        top: 0;
        z-index: 11;
        background: #fff;
    }

    /* 固定列样式优化 */
    :deep(.el-table__fixed-left) {
        box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
    }

    :deep(.el-table__fixed-right) {
        box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
    }

    /* 滚动条样式优化 */
    :deep(.el-table__body-wrapper)::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    :deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
        background: #f5f7fa;
        border-radius: 4px;
    }

    :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
        background: #c0c4cc;
        border-radius: 4px;
    }

    :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
        background: #909399;
    }
}

.text-overflow {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    vertical-align: top;
}

/* 回款节点名称样式 */
.receive-name {
    font-weight: 600;
    color: var(--el-color-success);
    background-color: var(--el-color-success-light-9);
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    display: inline-block;
}

/* 技术流程显示样式 */
.tech-flow-display {
    background-color: #f0f9ff;
    padding: 8px 12px;
    border-radius: 6px;
    border-left: 4px solid #409eff;
    font-weight: 500;
    color: #1e40af;
    display: block;
    line-height: 1.4;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .app-container {
        padding: 8px;
    }

    .card-header {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;
    }

    .card-header-left {
        flex-wrap: wrap;
        gap: 8px;
    }

    .week-info {
        padding: 6px 12px;
        justify-content: center;
    }

    .week-label {
        font-size: 13px;
    }
}
</style>
